package com.Ele_Demo.jackiez;


import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;


import com.Ele_Demo.jackiez.util.LogUtil;
import com.Ele_Demo.jackiez.db.DBOpenHelper;
import com.Ele_Demo.jackiez.download.DownloadFileAsync;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class Tab2 extends ListActivity {

	public static final int DIALOG_DOWNLOAD_PROGRESS = 1;
	public static final int DIALOG_UPLOAD_PROGRESS = 0;
	private ProgressDialog mProgressDialog;
	private DBOpenHelper mOpenHelper;
	public String[] s1;
	
	private List<Map<String, Object>> mData;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.tab2);
		//((TextView)this.findViewById(R.id.text)).setText("Tab2");
		//Button btn_download = (Button)findViewById(R.id.downloadbutton);
       // btn_download.setOnClickListener(this);
		String[] s=GetTheArray();
		//LogUtil.LogShow("[test]", "The split: "+s[0], LogUtil.DEBUG);
		mData = getData(s);
		MyAdapter adapter = new MyAdapter(this);
		setListAdapter(adapter);
	}
	
	//we use the post method to get the list,which is more safe
	public String[] GetTheArray(){
   		SharedPreferences passwdfile = getSharedPreferences( "USERPATH", 0);
		String path = passwdfile.getString("USERPATH", null);
        String uriAPI = "http://android.wuliu800.com/dblist.php?";
		HttpGet httpRequest = new HttpGet(uriAPI);
		String[] split1=null;

	      try
	      {
	        DefaultHttpClient httpclient = new DefaultHttpClient();
	        HttpResponse response;
	        HttpPost httpost = new HttpPost(uriAPI);
	        List <NameValuePair> nvps = new ArrayList <NameValuePair>();
	        nvps.add(new BasicNameValuePair("username", path));      
	        httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));        
	        response = httpclient.execute(httpost);
	        HttpEntity entity = response.getEntity();
	        String strResult = EntityUtils.toString(entity);
			split1 = strResult.split("#");
	      }
	      catch(Exception e)
	      {
	        e.printStackTrace();
	      }
		

        return split1;
	}
	
		 
	private List<Map<String, Object>> getData(String[] firstarray) {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		Map<String, Object> map = new HashMap<String, Object>();
		int size = firstarray.length;
		int i;
		String[] s2;
		//LogUtil.LogShow("[test]", "tt : "+firstarray[0], LogUtil.DEBUG);     
		//String test = "1,2,sdk,7,2.1-update1,2011-06-07,http://android.wuliu800.com/data/test@test.com/MyContacts.db";
		//String[] test11 = test.split(",");
		//LogUtil.LogShow("[test]", "test : "+test11[4], LogUtil.DEBUG);     

		for(i=0;i<size;i++){
			//LogUtil.LogShow("[test]", "The s1 : "+firstarray[i], LogUtil.DEBUG);     
			s2 = firstarray[i].split(",");
			//LogUtil.LogShow("[test]", "The s2 : "+s2[6], LogUtil.DEBUG);
			map = new HashMap<String, Object>();			
			map.put("account",s2[1]);	// messageer account
			map.put("phone", s2[2]);	// phone_model
			map.put("system", s2[4]);	//system
			map.put("date", s2[5]);		//	upload date
			map.put("durl",s2[6]);		//download url
			map.put("img", R.drawable.i3);
			list.add(map);
		}		
		return list;
	}
	
	// ListView 中某项被选中后的逻辑
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		
		LogUtil.LogShow("[Tab2]", "The listview item is"+(String)mData.get(position).get("account"), LogUtil.DEBUG);
		LogUtil.LogShow("[Tab2]", "The listview item is"+(String)mData.get(position).get("durl"), LogUtil.DEBUG);
		showInfo((String)mData.get(position).get("account"),
				(String)mData.get(position).get("phone"),
				(String)mData.get(position).get("date"),
				(String)mData.get(position).get("durl"),
				(String)mData.get(position).get("system"));
	}
	
	/**
	 * listview中点击按键弹出对话框
	 */
	public void showInfo(String account,String phone,String date,String durl,String system){
		final String download_url = durl;
        final SQLiteDatabase db = mOpenHelper.getReadableDatabase();
        final ContentResolver cr = getContentResolver();  
		new AlertDialog.Builder(this)
		.setTitle("我的listview")
		.setMessage("Date:"+date+"\nPhone:"+phone+"\nSystem:"+system+"\nRecords:"+account)
		.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				LogUtil.LogShow("[Tab2]", "durl "+download_url, LogUtil.DEBUG);  
				BeginToDownload(download_url);
		        Importer importer = new Importer();
		        importer.ImportContacts(db,cr);
			}
		})
		.setNegativeButton("No", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.cancel();
			}
		})
		.show();
		
	}	
	
	public final class ViewHolder{
		public ImageView img;
		public TextView phone;
		public TextView date;
		public TextView system;
		public TextView durl;
		public TextView account;
		//public Button viewBtn;

	}
	
	
	public class MyAdapter extends BaseAdapter{

		private LayoutInflater mInflater;
		
		
		public MyAdapter(Context context){
			this.mInflater = LayoutInflater.from(context);
		}
		
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return mData.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			
			final int position_id = position;
	        //Button btn_import = (Button)findViewById(R.id.view_btn);
			//mOpenHelper = new DBOpenHelper(btn_import.getContext());
	        //final SQLiteDatabase db = mOpenHelper.getReadableDatabase();
	        //final ContentResolver cr = getContentResolver();   
			ViewHolder holder = null;
			if (convertView == null) {
				
				holder=new ViewHolder();  
				
				convertView = mInflater.inflate(R.layout.vlist, null);
				holder.img = (ImageView)convertView.findViewById(R.id.img);
				holder.phone = (TextView)convertView.findViewById(R.id.phone);
				holder.date = (TextView)convertView.findViewById(R.id.date);
				holder.account = (TextView)convertView.findViewById(R.id.account);
				//holder.viewBtn = (Button)convertView.findViewById(R.id.view_btn);
				//holder.viewBtn.setFocusable(false);
				convertView.setTag(holder);
				//mOpenHelper = new DBOpenHelper(holder.viewBtn.getContext());
				
				
			}else {
				
				holder = (ViewHolder)convertView.getTag();
			}
			
	        //final SQLiteDatabase db = mOpenHelper.getReadableDatabase();
	        //final ContentResolver cr = getContentResolver();  
			holder.img.setBackgroundResource((Integer)mData.get(position).get("img"));
			holder.phone.setText((String)mData.get(position).get("phone"));
			holder.date.setText((String)mData.get(position).get("date"));
			holder.account.setText((String)mData.get(position).get("account"));
			//holder.durl.setText((String)mData.get(position).get("durl"));

			/*
			holder.viewBtn.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					//showInfo();	
					//LogUtil.LogShow("[Tab2]", "position is "+Integer.toString(position_id), LogUtil.DEBUG);
					//LogUtil.LogShow("[Tab2]", (String)mData.get(position_id).get("durl"), LogUtil.DEBUG);
					BeginToDownload((String)mData.get(position_id).get("durl"));
			        Importer importer = new Importer();
			        importer.ImportContacts(db,cr);
				}
			});
			*/
			return convertView;
		}
		
	}
	//the download
	public void BeginToDownload(String download_url){
    	try{
    		File dir = new File("/data/data/com.Ele_Demo.jackiez/databases/");
    		dir.mkdir();
    	}
    	catch(Exception e){
			LogUtil.LogShow("[download]", "the folder already been or creating error!", LogUtil.DEBUG);
    	}
    	//String url = "http://test.bjcargo.com/MyContacts2011427547.txt";
    	String url = download_url;
		//LogUtil.LogShow("[Tab2]", url, LogUtil.DEBUG);
    	new DownloadFileAsync().execute(url);
	}
	
    @Override
    protected Dialog onCreateDialog(int id) {
    switch (id) {
    case DIALOG_UPLOAD_PROGRESS:
    mProgressDialog = new ProgressDialog(this);
    mProgressDialog.setMessage("Uploading file..");
    //mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    mProgressDialog.setCancelable(false);
    mProgressDialog.show();
    return mProgressDialog;
    case DIALOG_DOWNLOAD_PROGRESS:
    mProgressDialog = new ProgressDialog(this);
    mProgressDialog.setMessage("Downloading file..");
    mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    mProgressDialog.setCancelable(false);
    mProgressDialog.show();
    return mProgressDialog;
    default:
    return null;
    }
    }
	//the downlaod async
	class DownloadFileAsync extends AsyncTask< String, String, String> {
		
		@Override
		protected void onPreExecute() {
		super.onPreExecute();
		showDialog(DIALOG_DOWNLOAD_PROGRESS);
		}
	
	 
		@Override
		protected String doInBackground(String... aurl) {
		int count;
		try {
		URL url = new URL(aurl[0]);
		URLConnection conexion = url.openConnection();
		conexion.connect();
		int lenghtOfFile = conexion.getContentLength();
		Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
		InputStream input = new BufferedInputStream(url.openStream());
		OutputStream output = new FileOutputStream("/data/data/com.Ele_Demo.jackiez/databases/MyContacts.db");
		byte data[] = new byte[1024];
		long total = 0;
		while ((count = input.read(data)) != -1) {
		total += count;
		publishProgress(""+(int)((total*100)/lenghtOfFile));
		output.write(data, 0, count);
		}
		output.flush();
		output.close();
		input.close();
		} catch (Exception e) {
		Log.e("error",e.getMessage().toString());
		System.out.println(e.getMessage().toString());
		}
		return null;
		}
		
	
		protected void onProgressUpdate(String... progress) {
		Log.d("ANDRO_ASYNC",progress[0]);
		mProgressDialog.setProgress(Integer.parseInt(progress[0]));
		}

		 
		@Override
		protected void onPostExecute(String unused) {
		dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
		}
		}
    
}
